//
//  OpenSDK_UIManager.m
//  OpenSDK
//
//  Created by wyht－ios－dev on 16/9/7.
//  Copyright © 2016年 WYHT. All rights reserved.
//

#import "OpenSDK_UIManager.h"
#import "OpenSDK.h"
#import "OpenSDK_DataManager.h"
#import "OpenSDK_LoginManager.h"
#import "OpenSDK_Enum.h"
#import "OpenSDK_DataKeys.h"
#import "OpenSDK_StatusManager.h"
#import "OpenSDK_PayManager.h"
#import "OpenSDK_StatisticsManager.h"

#import "OpenSDK_AccountRecord.h"
#import "OpenSDK_ConfirmDialog.h"
#import "OpenSDK_LoginMobileView.h"
#import "OpenSDK_QuickLoginView.h"
#import "OpenSDK_BindMobileView.h"
#import "OpenSDK_PayView.h"

#import "OpenSDK_UIUtil.h"
#import "OPKTracking.h"
#import "OPKCoreConfiguration.h"

#import "OpenSDK_LoginProtocol.h"
#import "OpenSDK_LoginLoadingView.h"
#import "OpenSDK_Toast.h"

#import "OPKOneKeyParentViewController.h"
#import "OpenSDK_LoginInvalidView.h"

@implementation OpenSDK_UIManager

{
    UINavigationController *navController;
    BOOL isOneKeyOnTheBack;
}

static OpenSDK_UIManager *instance = nil;

+(instancetype) getInstance {
    if(instance==nil) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            instance = [[self alloc] init];
        });
    }
    return instance;
}

- (UINavigationController *)navigationController {
    return navController;
}

-(void) createNavControllerWithStoryBoard:(NSString *)storyboard withVCId:(NSString *)vcId {
    UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:storyboard bundle:nil];
    UIViewController *vc = (UIViewController *) [loginStoryboard instantiateViewControllerWithIdentifier:vcId];
    [self createNavControllerWithViewController:vc];
}


-(void) createNavControllerWithViewController:(UIViewController *)vc {
    if (vc == nil) {
        return;
    }
    if (navController != nil) {
        [navController pushViewController:vc animated:NO];
    } else {
        navController = [[UINavigationController alloc]initWithRootViewController:vc];
        [navController setNavigationBarHidden:YES];
        navController.modalPresentationStyle = UIModalPresentationOverFullScreen;
        UIViewController *root = [OpenSDK_UIUtil getCurrentVC];
        [root presentViewController:navController animated:NO completion:nil];
    }
}

-(void) showNextUIWithStoryBoard:(NSString *)storyboard withVCId:(NSString *)vcId {
    UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:storyboard bundle:nil];
    UIViewController *vc = (UIViewController *) [loginStoryboard instantiateViewControllerWithIdentifier:vcId];
    [self showNextUIWithViewController:vc];
}

-(void)  showNextUIWithViewController:(UIViewController *)vc {
    if (navController == nil) {
        [self createNavControllerWithViewController:vc];
        return;
    }
    [navController pushViewController:vc animated:NO];
}

- (void)showViewControllerWithSBId:(NSString *)sbId vcid:(NSString *)vcid {
    for (UIViewController *cvc in navController.viewControllers) {
        if ([cvc isKindOfClass:NSClassFromString(vcid)]) {
            [navController popToViewController:cvc animated:NO];
            return;
        }
    }
    [self showNextUIWithStoryBoard:sbId withVCId:vcid];
}

- (void)showViewController:(UIViewController *)viewController {
    for (UIViewController *cvc in navController.viewControllers) {
        if ([cvc isEqual:viewController]) {
            [navController popToViewController:cvc animated:NO];
            return;
        }
    }
    [self showNextUIWithViewController:viewController];
}

-(void) initLoginUI {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self->navController != nil) {
            return;
        }
        [[OpenSDK_StatisticsManager getInstance] startLogin];
        
        // 激活码开关判断
        if ([OpenSDK_DataManager getInstance].needActiveCodeFlag) {
            // 需要激活码
            [[OpenSDK_LoginManager getInstance] checkActivationCodeWithDelegate:^(BOOL isBind, NSString *err) {
                if (!isBind) {
                    // 没有绑定激活码，弹出绑定界面
                    UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:@"LoginMain" bundle:nil];
                    UIViewController *vc = (UIViewController *) [loginStoryboard instantiateViewControllerWithIdentifier:@"OpenSDK_ActivationCodeView"];
                    vc.modalPresentationStyle=UIModalPresentationCustom;
                    [[OpenSDK_UIUtil getCurrentVC] presentViewController:vc animated:NO completion:nil];
                } else {
                    // 已经绑定激活码，直接弹登录界面
                    [self showLoginUI];
                }
            }];
        } else {
            // 不需要激活码，直接弹登录界面
            [self showLoginUI];
        }
    });
}

-(void) showLoginUI {
    // 登录界面，首页
    OpenSDK_AccountRecord *curAccount = [[OpenSDK_DataManager getInstance] getCurAccount];
    if (curAccount == nil) {
        [self showDefaultLoginView];
    } else {
//        if (curAccount.accountType == OpenSDKAccountTypeGuest &&) {
//            // 当前账号是游客，弹出提示，绑定手机号
//            [OpenSDK_ConfirmDialog showWithMessage:@"为了避免您的账号丢失，请尽快绑定手机号"
//                                         okBtnName:@"绑定手机"
//                                     cancelBtnName:@"快速登录"
//                                          delegate:^(BOOL result) {
//                                              if (result) {
//                                                  // 跳转到绑定手机号界面
//                                                  [self createNavControllerWithStoryBoard:@"LoginMain" withVCId:@"OpenSDK_BindMobileView"];
//                                              } else {
//                                                  // 跳转到快捷登录界面
//                                                  [self createNavControllerWithStoryBoard:@"LoginMain" withVCId:@"OpenSDK_QuickLoginView"];
//                                              }
//                                          } root:nil];
//        } else {
            [self createNavControllerWithStoryBoard:@"LoginMain" withVCId:@"OpenSDK_QuickLoginView"];
//        }
    }
}

- (void)showDefaultLoginView {
    if ([OpenSDK_DataManager getInstance].isAppstoreReview){
        [self createNavControllerWithStoryBoard:@"LoginMain" withVCId:@"OpenSDK_LoginMailView"];
    }else{
        if ([[OpenSDK_DataManager getInstance].supportLoginTypes containsObject:OpenSDK_S_ONE_KEY]){
            [self showOneKeyLogin];
        }else{
            [self createNavControllerWithStoryBoard:@"LoginMain" withVCId:@"OpenSDK_LoginMobileView"];
            
        }
    }
}

- (void)showOneKeyLogin {
    [self showViewControllerWithSBId:@"LoginMain" vcid:@"OPKOneKeyParentViewController"];
}

- (void)showMoboleViewControllerWithAccount:(OpenSDK_AccountRecord *)account canBack:(BOOL)canBack {
    // 去手机号登录
    UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:@"LoginMain" bundle:nil];
    OpenSDK_LoginMobileView *vc = (OpenSDK_LoginMobileView *) [loginStoryboard instantiateViewControllerWithIdentifier:@"OpenSDK_LoginMobileView"];
    if (account.mobile != nil && account.mobile.length > 0) {
        vc.inputMobile = account.mobile;
    }
    vc.cantBack = !canBack;
    [self showViewController:vc];
}

- (void)showSwitchAccountUI {
    // 登录界面，首页
    OpenSDK_AccountRecord *curAccount = [[OpenSDK_DataManager getInstance] getCurAccount];
    if (curAccount == nil) {
        // 没有历史账号，则跳转到手机登录界面
        [self createNavControllerWithStoryBoard:@"LoginMain" withVCId:@"OpenSDK_LoginMobileView"];
    } else {
        // 跳转到快捷登录界面
        [self createNavControllerWithStoryBoard:@"LoginMain" withVCId:@"OpenSDK_QuickLoginView"];
    }
}

- (void)showRealUI {
    // 弹出实名认证框
    OpenSDK_AccountRecord *account = [OpenSDK_DataManager getInstance].getCurAccount;
    if (account.isMobile == false && account.needMobile != 0) {
        // 实名认证(需要手机号)
        [self createNavControllerWithStoryBoard:@"LoginMain" withVCId:@"OpenSDK_RealNameMobileView"];
    } else {
        // 实名认证(无需手机号)
        [self createNavControllerWithStoryBoard:@"LoginMain" withVCId:@"OpenSDK_RealNameView"];
    }
}

- (void)showBindPhoneUI {
    [self createNavControllerWithStoryBoard:@"LoginMain" withVCId:@"OpenSDK_BindMobileView"];
}


-(void) closeUI {
    if (navController) {
        [navController dismissViewControllerAnimated:NO completion:nil];
        navController = nil;
    }
}

- (void)goBack {
    if (navController) {
        if (navController.viewControllers.count <= 1) {
            [self closeUI];
        } else {
            [navController popViewControllerAnimated:NO];
        }
    }
}

-(void) initPayUIWithPayInfo:(OpenSDK_PayInfo *)payInfo {
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([OpenSDK_StatusManager getInstance].payStatus) {
            // 正在支付，请勿重复点击支付
            if ([OpenSDK getInstance].delegate) {
                [[OpenSDK getInstance].delegate openSDKPayWithCode:OpenSDK_PAY_FAIL orderInfo:nil errStr:@"正在支付，请勿重复点击支付"];
            }
            return;
        }
        [[OpenSDK_StatusManager getInstance] setPayStatus:YES];
        
        NSArray* configInfo = [OpenSDK_DataManager getInstance].supportXyzTypes;
        if (configInfo == nil || configInfo.count == 0) {
            // 没有支付方式，结束支付操作，返回失败
            [[OpenSDK_PayManager getInstance] callbackPayFail:@"抱歉，无法支付" withOrder:nil];
            return;
        }
        
        OpenSDK_AccountRecord *curAccount = [[OpenSDK_DataManager getInstance] getCurAccount];
        if (curAccount == nil) {
            // 没有登录，结束支付操作，返回失败
            [[OpenSDK_PayManager getInstance] callbackPayFail:@"请先登录，再进行支付" withOrder:nil];
            return;
        }
        
        // 游客支付时，提示去绑定手机号
        if (curAccount.accountType == OpenSDKAccountTypeGuest) {
            [OpenSDK_ConfirmDialog showWithMessage:@"游客账号有数据丢失的风险，请绑定手机号码后再充值"
                                         okBtnName:@"绑定手机"
                                     cancelBtnName:[OpenSDK_DataManager getInstance].forbidGuestPayFlag ? @"取消" : @"继续支付"
                                          delegate:^(BOOL result) {
                                              if (result) {
                                                  // 跳转到绑定手机号界面
                                                  UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:@"LoginMain" bundle:nil];
                                                  OpenSDK_BindMobileView *vc = (OpenSDK_BindMobileView *) [loginStoryboard instantiateViewControllerWithIdentifier:@"OpenSDK_BindMobileView"];
                                                  vc.order = payInfo;
                                                  [self createNavControllerWithViewController:vc];
                                                  [[OpenSDK_StatusManager getInstance] setPayStatus:NO];
                                              } else {
                                                  if ([OpenSDK_DataManager getInstance].forbidGuestPayFlag) {
                                                      // 上报支付取消统计
                                                      [[OpenSDK_StatisticsManager getInstance] collectPayCancelWithCpOrderId:payInfo.appData detail:OPENSDK_STATS_DETAIl_PAY_CANCEL_BIND];
                                                      // 取消支付（禁止游客支付）
                                                      [[OpenSDK_PayManager getInstance] callbackPayCancel];
                                                  } else {
                                                      // 继续支付
                                                      [self showPayUI:payInfo];
                                                  }
                                              }
                                          } root:nil];
        } else {
            // 非游客，直接调起支付
            [self showPayUI:payInfo];
        }
    });
}

-(void) showPayUI:(OpenSDK_PayInfo *)payInfo {
    NSArray* configInfo = [OpenSDK_DataManager getInstance].supportXyzTypes;
    if([configInfo count] ==1) {
        // 只有一种支付方式，直接调用sdk支付
        [[OpenSDK_PayManager getInstance] pay:payInfo serverName:[configInfo objectAtIndex:0]];
    } else {
        // 统计展示支付方式选择界面
        [[OpenSDK_StatisticsManager getInstance] collectPayActionWithType:OPENSDK_STATS_PAY_SELECT_UI
                                                               cpOrderId:payInfo.appData
                                                                  detail:nil];
        // 显示服务器配置的支付方式列表
        UIViewController *root = [OpenSDK_UIUtil getCurrentVC];
        UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:@"PayMain" bundle:nil];
        OpenSDK_PayView *payView = (OpenSDK_PayView *) [loginStoryboard instantiateViewControllerWithIdentifier:@"OpenSDK_PayView"];
        [payView setPayInfo:payInfo wihtConfig:configInfo];
        [root presentViewController:payView animated:false completion:nil];
    }
}

-(void) loginInvalid{
    OpenSDK_LoginInvalidView *loginInvalidView = [[OpenSDK_LoginInvalidView alloc] init];
    loginInvalidView.complateBlock = ^(void){
        [[OpenSDK getInstance] logout];
    };
    [self createNavControllerWithViewController:loginInvalidView];
}

#pragma mark --统一处理其他登录显示 和 执行
//统一处理登录非此即彼显示方式
- (void)handleOtherLoginTypesWithButton:(UIButton *)button curLoginType:(NSString *)curLoginType {
    
    //id<OpenSDK_LoginProtocol> sdkClass =  [[OpenSDK_DataManager getInstance].supportSDKServerNames valueForKey:@""];

    NSMutableArray *supportLoginTypes = [OpenSDK_DataManager getInstance].supportLoginTypes.mutableCopy;
    if (supportLoginTypes == nil || supportLoginTypes.count == 0 || (supportLoginTypes.count == 1 && [supportLoginTypes containsObject:curLoginType])) {
        button.hidden = YES;
        return;
    }
    
    button.hidden = NO;
    if ([supportLoginTypes containsObject:curLoginType]) {
        [supportLoginTypes removeObject:curLoginType];
    }
    if (supportLoginTypes.count == 1) {
        NSString *loginType = [supportLoginTypes firstObject];
//        id<OpenSDK_LoginProtocol> sdkClass =  [[OpenSDK_DataManager getInstance].supportSDKServerNames valueForKey:loginType];
        [button setTitle:[self getDisplayLoginType:loginType] forState:UIControlStateNormal];
    } else {
        [button setTitle:@"其他登录方式" forState:UIControlStateNormal];
    }
}

- (NSString *)getDisplayLoginType:(NSString *)loginType {
    NSString *displayName = @"其他登录方式";
    if ([loginType isEqualToString:OpenSDK_S_DYNAMIC]) {
        displayName = @"手机验证码登录";
    } else if ([loginType isEqualToString:OpenSDK_S_ONE_KEY]) {
        displayName = @"本机号码一键登录";
    } else if ([loginType isEqualToString:OpenSDK_S_ACCOUNT]) {
        displayName = @"密码登录";
    } else if ([loginType isEqualToString:OpenSDK_S_TEMPORARY]) {
        displayName = @"游客登录";
    } else if ([loginType isEqualToString:@"AppleLogin"]) {
        displayName = @"苹果登录";
    } else if ([loginType isEqual:@"QQ"]) {
        displayName = @"QQ登录";
    } else if ([loginType isEqual:@"WeChatLogin"]) {
        displayName = @"微信登录";
    } else if ([loginType isEqualToString:OpenSDK_S_FACEBOOKSDK] || [loginType isEqualToString:OpenSDK_S_FACEBOOKSDK_ACCOUNTKIT]) {
        displayName = @"Facebook登录";
    }
    return displayName;
}

//统一处理登录非此即彼跳转和登录
- (void)handleOtherLoginMethodWithCurLoginType:(NSString *)curLoginType contranctChecked:(BOOL)contranctChecked {
    
    NSMutableArray *supportLoginTypes = [OpenSDK_DataManager getInstance].supportLoginTypes.mutableCopy;
    if (supportLoginTypes == nil || supportLoginTypes.count == 0 || (supportLoginTypes.count == 1 && [supportLoginTypes containsObject:curLoginType])) {
        return;
    }
    
    if ([supportLoginTypes containsObject:curLoginType]) {
        [supportLoginTypes removeObject:curLoginType];
    }
    if (supportLoginTypes.count == 1) {
        NSString *loginType = [supportLoginTypes firstObject];
        [self loginWithType:loginType contranctChecked:contranctChecked];
    } else {
        [[OPKTracking shared] event:OPKEventLoginOther];
        
        // 跳转到更多登录界面
        [[OpenSDK_UIManager getInstance] showViewControllerWithSBId:@"LoginMain" vcid:@"OpenSDK_LoginMoreView"];
    }
}

- (void)loginWithType:(NSString *)loginType contranctChecked:(BOOL)contranctChecked {
    if ([OpenSDK_S_DYNAMIC isEqualToString:loginType]) {
        //手机验证码登录界面
        // 统计
        [[OPKTracking shared] event:OPKEventLoginMobile];
        [self showViewControllerWithSBId:@"LoginMain" vcid:@"OpenSDK_LoginMobileView"];
    } else if ([OpenSDK_S_ACCOUNT isEqualToString:loginType]) {
        //邮箱登录界面
        // 统计
        [[OPKTracking shared] event:OPKEventLoginPassword];
        [self showViewControllerWithSBId:@"LoginMain" vcid:@"OpenSDK_LoginMailView"];
    } else if ([OpenSDK_S_TEMPORARY isEqualToString:loginType]) {
        // 游客登录
        // 先弹出loading框
        UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:@"LoginMain" bundle:nil];
        OpenSDK_LoginLoadingView *vc = (OpenSDK_LoginLoadingView *) [loginStoryboard instantiateViewControllerWithIdentifier:@"OpenSDK_LoginLoadingView"];
        vc.accoutnName = @"游客";
        [self.navigationController pushViewController:vc animated:NO];
        // 再调用登录接口
        [[OpenSDK_LoginManager getInstance] loginWithGuest:^(BOOL result, OpenSDK_AccountRecord *account, long errorNo, NSString *err) {
            if (!result) {
                // 登录失败
                [[[OpenSDK_iToast makeText:err] setDuration:2000] show];
            }
            [vc loginResultCallback:result account:account];
        }];
    }
    else if ([OpenSDK_S_ONE_KEY isEqualToString:loginType]) {
        [[OpenSDK_UIManager getInstance] showOneKeyLogin];
    }
    else if ([OpenSDK_S_FACEBOOKSDK isEqualToString:loginType]) {
        // TODO
    } else if ([OpenSDK_S_FACEBOOKSDK_ACCOUNTKIT isEqualToString:loginType]) {
        // TODO
    } else {
        if ([loginType isEqual:@"QQ"]) {
            [[OPKTracking shared] event:OPKEventLoginQQ];
        } else if ([loginType isEqual:@"WeChatLogin"]) {
            [[OPKTracking shared] event:OPKEventLoginWeChat];
        } else if ([loginType isEqual:@"AppleLogin"]) {
            [[OPKTracking shared] event:OPKEventLoginApple];
        }
        // 是否已经同意用户协议
        if (contranctChecked == NO) {
            return;
        }
        id<OpenSDK_LoginProtocol> sdk = [[OpenSDK_DataManager getInstance].supportSDKServerNames objectForKey:loginType];
        // 先弹出loading框
        UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:@"LoginMain" bundle:nil];
        OpenSDK_LoginLoadingView *vc = (OpenSDK_LoginLoadingView *) [loginStoryboard instantiateViewControllerWithIdentifier:@"OpenSDK_LoginLoadingView"];
        vc.accoutnName = [sdk getDisplaySdkName];
        [self.navigationController pushViewController:vc animated:NO];
        
        // 再调用第三方登录接口
        [[OpenSDK_LoginManager getInstance] loginWithPlatform:loginType delegate:^(BOOL result, OpenSDK_AccountRecord *account, long errorNo, NSString *err) {
            if (!result) {
                // 登录失败
                [[[OpenSDK_iToast makeText:err] setDuration:2000] show];
            }
            [vc loginResultCallback:result account:account];
        }];
    }
}



@end
